const productApi = require('../../api/product')

Page({
  data: {
    recordList: [],
    loading: false,
    hasMore: true,
    page: 1,
    size: 10,
    keyword: '',
    searchValue: '',
    refreshing: false,
    showCancelModal: false,
    selectedRecord: null
  },

  onLoad() {
    this.loadPurchaseRecords()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  /**
   * 加载购买记录
   */
  async loadPurchaseRecords(isRefresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        page: isRefresh ? 1 : this.data.page,
        size: this.data.size,
        keyword: this.data.keyword
      }

      const result = await productApi.getMyPurchaseRecords(params)

      if (result && result.records) {
        // 预处理数据，格式化价格和时间
        const processedRecords = result.records.map(record => ({
          ...record,
          unitPriceFormatted: this.formatPrice(record.unitPrice),
          totalAmountFormatted: this.formatPrice(record.totalAmount),
          createTimeFormatted: this.formatTime(record.createTime),
          statusText: this.getStatusText(record.purchaseStatus),
          statusClass: this.getStatusClass(record.purchaseStatus)
        }))

        const newList = isRefresh ? processedRecords : [...this.data.recordList, ...processedRecords]

        this.setData({
          recordList: newList,
          hasMore: result.records.length === this.data.size,
          page: isRefresh ? 2 : this.data.page + 1,
          loading: false,
          refreshing: false
        })
      } else {
        this.setData({
          loading: false,
          refreshing: false,
          hasMore: false
        })
      }
    } catch (error) {
      console.error('加载购买记录失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      this.setData({
        loading: false,
        refreshing: false
      })
    }
  },

  /**
   * 刷新数据
   */
  refreshData() {
    this.setData({
      recordList: [],
      page: 1,
      hasMore: true,
      refreshing: true
    })
    this.loadPurchaseRecords(true)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadPurchaseRecords()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  /**
   * 执行搜索
   */
  onSearch() {
    this.setData({
      keyword: this.data.searchValue,
      recordList: [],
      page: 1,
      hasMore: true
    })
    this.loadPurchaseRecords(true)
  },

  /**
   * 清空搜索
   */
  onClearSearch() {
    this.setData({
      searchValue: '',
      keyword: '',
      recordList: [],
      page: 1,
      hasMore: true
    })
    this.loadPurchaseRecords(true)
  },

  /**
   * 查看记录详情
   */
  onRecordTap(e) {
    const { record } = e.currentTarget.dataset

    wx.showModal({
      title: '购买详情',
      content: `商品：${record.productName}\n数量：${record.purchaseQuantity}件\n单价：¥${record.unitPriceFormatted || this.formatPrice(record.unitPrice)}\n总计：¥${record.totalAmountFormatted || this.formatPrice(record.totalAmount)}\n状态：${record.statusText || this.getStatusText(record.purchaseStatus)}\n时间：${record.createTimeFormatted || this.formatTime(record.createTime)}`,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 显示取消确认弹窗
   */
  showCancelModal(e) {
    const { record } = e.currentTarget.dataset
    
    if (record.purchaseStatus !== 1) {
      wx.showToast({
        title: '只能取消已完成的订单',
        icon: 'none'
      })
      return
    }

    this.setData({
      showCancelModal: true,
      selectedRecord: record
    })
  },

  /**
   * 隐藏取消确认弹窗
   */
  hideCancelModal() {
    this.setData({
      showCancelModal: false,
      selectedRecord: null
    })
  },

  /**
   * 确认取消订单
   */
  async confirmCancel() {
    const { selectedRecord } = this.data
    
    if (!selectedRecord) return

    try {
      await productApi.cancelPurchaseRecord(selectedRecord.id)
      
      wx.showToast({
        title: '取消成功',
        icon: 'success'
      })
      
      this.hideCancelModal()
      this.refreshData()
      
    } catch (error) {
      console.error('取消订单失败:', error)
      wx.showToast({
        title: error.message || '取消失败',
        icon: 'none'
      })
    }
  },

  /**
   * 重新购买
   */
  onRepurchase(e) {
    const { record } = e.currentTarget.dataset
    
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${record.productId}`
    })
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    switch (status) {
      case 1:
        return '已完成'
      case 2:
        return '已取消'
      default:
        return '未知'
    }
  },

  /**
   * 获取状态样式类
   */
  getStatusClass(status) {
    switch (status) {
      case 1:
        return 'status-completed'
      case 2:
        return 'status-cancelled'
      default:
        return 'status-unknown'
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timeStr) {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  /**
   * 格式化价格
   */
  formatPrice(price) {
    if (price === null || price === undefined || price === '') {
      return '0.00'
    }
    const numPrice = parseFloat(price)
    if (isNaN(numPrice)) {
      return '0.00'
    }
    return numPrice.toFixed(2)
  },

  /**
   * 去购买商品
   */
  onGoShopping() {
    wx.switchTab({
      url: '/pages/product-list/product-list'
    })
  }
}) 